package com.leyou.favorite.service;

import com.leyou.auth.entity.UserInfo;
import com.leyou.common.pojo.utils.JsonUtils;
import com.leyou.favorite.client.CategoryClient;
import com.leyou.favorite.client.GoodsClient;
import com.leyou.favorite.interceptor.LoginInterceptor;
import com.leyou.favorite.mapper.FavoriteMapper;
import com.leyou.favorite.pojo.Favorite;
import com.leyou.item.pojo.Category;
import com.leyou.item.pojo.Sku;
import com.leyou.item.pojo.Spu;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author CHERRY
 * @date 2018-09-21-14:21
 */
@Service
public class FavoriteService {

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private GoodsClient goodsClient;

    @Autowired
    private CategoryClient categoryClient;

    @Autowired
    private StringRedisTemplate template;

    private static final String PRE_KEY = "leyou:track:";

    public void addMyFavorite(Long skuId) {

        //查询登录用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();

        //查询sku 数据
        Sku sku = this.goodsClient.querySkuById(skuId);


        //生成收藏id(雪花算法)
        //long id = idWorker.nextId();

        //设置收藏表数据
        Favorite favorite = new Favorite();
        favorite.setSpuId(sku.getSpuId());
        favorite.setUserId(userInfo.getId());
        favorite.setImage(StringUtils.isBlank(sku.getImages()) ? "" : sku.getImages().split(",")[0]);
        favorite.setPrice(sku.getPrice());
        favorite.setTitle(sku.getTitle());
        favorite.setOwnSpec(sku.getOwnSpec());
        favorite.setSkuId(sku.getId());
        favorite.setCreateTime(new Date());

        //通用mapper 添加到数据库
        this.favoriteMapper.insert(favorite);

    }

    /**
     * 查看关注
     *
     * @return
     */
    public List<Favorite> queryMyFavorite() {
        //查询登录用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();

        //查询收藏数据,时间倒序
        List<Favorite> favorites = this.favoriteMapper.selectFavoriteByUserIdAndDesc(userInfo.getId());

        //根据skuId 查询最新商品价格,是否有效
        favorites.forEach(favorite -> {

            //查询sku
            Sku sku = this.goodsClient.querySkuById(favorite.getSkuId());
            //查询spu
            Spu spu = this.goodsClient.querySpuById(sku.getSpuId());
            //查询三级分类信息
            Category category = this.categoryClient.queryCategoryById(spu.getCid3());

            //设置最新价格，是否失效以及分类名称
            favorite.setNewPrice(sku.getPrice());
            favorite.setEnable(sku.getEnable());
            favorite.setCname(category.getName());
        });

        //返回
        return favorites;
    }

    /**
     * 添加我的历史足迹
     *
     * @param favorite
     */
    public void addMyTrack(Favorite favorite) {

        //查询登录用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        String key = PRE_KEY + userInfo.getId().toString();

        //查询sku 数据
        Sku sku = this.goodsClient.querySkuById(favorite.getSkuId());

        //生成收藏id(雪花算法)
        //long id = idWorker.nextId();

        //设置

        //favorite.setId(id);
        favorite.setSpuId(sku.getSpuId());
        favorite.setUserId(userInfo.getId());
        favorite.setImage(StringUtils.isBlank(sku.getImages()) ? "" : sku.getImages().split(",")[0]);
        favorite.setPrice(sku.getPrice());
        favorite.setTitle(sku.getTitle());
        favorite.setOwnSpec(sku.getOwnSpec());
        favorite.setSkuId(sku.getId());
        favorite.setCreateTime(new Date());

        BoundHashOperations<String, Object, Object> hashOps = template.boundHashOps(key);

        hashOps.put(favorite.getSkuId().toString(), JsonUtils.serialize(favorite));

    }

    /**
     * 查询历史足迹
     *
     * @return
     */
    public List<Favorite> queryMyTrack() {

        //查询登录用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        String key = PRE_KEY + userInfo.getId().toString();

        if (!template.hasKey(key)) {
            return null;
        }

        BoundHashOperations<String, Object, Object> hashOps = template.boundHashOps(key);
        //redis 存储集合
        List<Object> collect = hashOps.values();

        if (CollectionUtils.isEmpty(collect)) {
            return null;
        }


        List<Favorite> favorites = collect.stream().map(favorite -> JsonUtils.parse(favorite.toString(), Favorite.class)).collect(Collectors.toList());

        //查看并返回最新商品信息
        favorites.forEach(favorite -> {
            Sku sku = this.goodsClient.querySkuById(favorite.getSkuId());

            //是否下架，最新价格
            favorite.setEnable(sku.getEnable());
            favorite.setNewPrice(sku.getPrice());

        });


        Collections.sort(favorites, (Favorite o1, Favorite o2) -> {
            int result = (int) (o2.getCreateTime().getTime() - o1.getCreateTime().getTime());
            return result;
        });
        //排序 小到大
        //Collections.sort(collect, Comparator.comparing(Favorite::getCreateTime));
        return favorites;
    }

    /**
     * 取消当前用户关注
     *
     * @param skuId
     */
    public void deleteMyFavorite(Long skuId) {

        //获取用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();

        Favorite favorite = new Favorite();

        favorite.setUserId(userInfo.getId());
        favorite.setSkuId(skuId);

        this.favoriteMapper.delete(favorite);
    }

    /**
     * 查询登录用户是否关注该商品
     *
     * @param skuId
     * @return
     */
    public Boolean queryIsFavorite(Long skuId) {

        //获取用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();

        Favorite favorite = new Favorite();

        favorite.setUserId(userInfo.getId());
        favorite.setSkuId(skuId);

        return this.favoriteMapper.selectCount(favorite) == 1;
    }
}
